#include "sym4sqrnetworkconn.h"

#include <QtNetwork>

Sym4sqrNetworkConn::Sym4sqrNetworkConn(QObject *parent) :
    QObject(parent)
{
    isLoggedIn = false;
}

void Sym4sqrNetworkConn::login(QString username, QString password)
{
    this->username = username;
    this->password = password;
    sendNetworkRequest(QUrl("http://api.foursquare.com/v1/user"));
}

void Sym4sqrNetworkConn::sendNetworkRequest(QUrl url)
{
    QNetworkRequest request;
    request.setRawHeader("Authorization", "Basic " +
                             QByteArray(QString("%1:%2").arg(username).arg(password).toAscii()).toBase64());
    request.setUrl(url);
    QNetworkReply *reply = qnam.get(request);
    connect(reply, SIGNAL(readyRead()), this, SLOT(networkReplyCallback()));
    connect(&qnam, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
            this, SLOT(slotAuthenticationRequired(QNetworkReply*, QAuthenticator*)));
}

void Sym4sqrNetworkConn::networkReplyCallback()
{
    QNetworkReply *reply = (QNetworkReply*) QObject::sender();
    xml.clear();
    xml.addData(reply->readAll());
    parseXMLLogin();
}

void Sym4sqrNetworkConn::slotAuthenticationRequired(QNetworkReply*, QAuthenticator *authenticator)
{
    authenticator->setUser(username);
    authenticator->setPassword(password);
}

void Sym4sqrNetworkConn::parseXMLLogin()
{
    while (!xml.atEnd()) {
        xml.readNext();
        if (xml.isStartElement()) {
            if (xml.name() == "unauthorized") {
                isLoggedIn = false;
                qDebug() << "Wrong username/password.";
            }
            else {
                isLoggedIn = true;
                qDebug() << "Successfully logged in!";
                emit loginStatusChanged(isLoggedIn);
            }
            return;
        }
    }
}
